from flask import Flask, request, jsonify, send_from_directory
import os
from flask_cors import CORS
from PIL import Image
import numpy as np

app = Flask(__name__)
CORS(app)  # 启用跨域,否则能打开index但是不能上传图片

# 获取当前文件所在目录的绝对路径
BASE_DIR = os.path.dirname(os.path.abspath(__file__))

@app.route('/')
def serve_index():
    return send_from_directory(BASE_DIR, 'index.html')

@app.route('/<path:filename>')
def serve_static(filename):
    return send_from_directory(BASE_DIR, filename)

@app.route('/upload-map', methods=['POST'])
def upload_map():
    if 'mapImage' not in request.files:
        return jsonify({"error": "No file provided"}), 400
        
    file = request.files['mapImage']
    try:
        # 处理图片
        img = Image.open(file.stream).convert('L')  # 转为灰度
        #.convert('L')：调用 Image 对象的 convert 方法，将图像转换为灰度模式。'L' 模式表示每个像素由一个 8 位整数表示，范围从 0（黑色）到 255（白色）。
        img = img.resize((52, 23))  # 匹配前端网格尺寸
        
        # 生成网格数据
        pixels = np.array(img)
        grid_data = (pixels < 128)  # 二值化
        
        # 构建完整单元格结构
        cells = []
        for x in range(grid_data.shape[0]):
            row = []
            for y in range(grid_data.shape[1]):
                row.append({
                    "isWall": bool(grid_data[x][y]),
                    "x": x,
                    "y": y,
                    "element": None  # 前端会填充这个字段
                })
            cells.append(row)
        
        return jsonify({
            "success": True,
            "cells": cells
        })
        
    except Exception as e:
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500

if __name__ == '__main__':
    app.run(port=5000, debug=True)
# 注意,在grid.js中有:const response = await fetch('http://localhost:5000/upload-map',这需要保证这几个定义的端口完全一致
# http://127.0.0.1:5000/index.html
# http://127.0.0.1:5000都可以